package com.jp.knowledge.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.HotSearchAdapter;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PopularSearchModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/3/31.
 */

public class SearchBgView extends FrameLayout implements ResultSubscriber.OnResultListener, View.OnClickListener {

    private Context context;

    private View contentView;
    private ImageView clearHistory;
    private FlowLayout searchHistoryView;
    private RecyclerView hotSearchView;

    private int type;
    private FileCacheManager cacheManager;
    private String searchHistoryCachePath;
    private String hotSearchCachePath;
    private List<PopularSearchModel> hotSearchModels;
    private HotSearchAdapter hotSearchAdapter;

    private OnClickListener searchHistoryItemClickListener;

    public SearchBgView(Context context) {
        super(context);
        init(context);
    }

    public SearchBgView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public SearchBgView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        this.context = context;
        this.contentView = inflate(context, R.layout.search_bg_view, this);
        this.clearHistory = (ImageView) contentView.findViewById(R.id.search_history_clean);
        this.searchHistoryView = (FlowLayout) contentView.findViewById(R.id.search_history_flowview);
        this.hotSearchView = (RecyclerView) contentView.findViewById(R.id.search_popular_view);
        this.type = 0;
        this.hotSearchModels = new ArrayList<>();

        this.clearHistory.setVisibility(View.GONE);

        this.cacheManager = new FileCacheManager();
        this.searchHistoryCachePath = context.getCacheDir() + "/searchHistory_" + type + ".dat";
        this.hotSearchCachePath = context.getCacheDir() + "/hotSearch_" + type + ".dat";

        this.clearHistory.setOnClickListener(this);
        this.hotSearchView.setHasFixedSize(true);
        this.hotSearchAdapter = new HotSearchAdapter(context, hotSearchModels);
        this.hotSearchView.setAdapter(hotSearchAdapter);
        this.hotSearchAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
//                if(searchClickListener != null)
//                    searchClickListener.onSearchClick(hotSearchModels.get(position).getTagName());
                PopularSearchModel popularSearchModel = hotSearchModels.get(position);

            }
        });
        this.hotSearchView.setLayoutManager(new LinearLayoutManager(context){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        this.searchHistoryItemClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(searchClickListener != null)
                    searchClickListener.onSearchClick(((TextView)v).getText().toString());
            }
        };
    }

    public void init(int type){
        this.type = type;
        this.searchHistoryCachePath = context.getCacheDir() + "/searchHistory_" + this.type + ".dat";
        this.hotSearchCachePath = context.getCacheDir() + "/hotSearch_" + this.type + ".dat";
        readSearchHistroyCache();       // 读取搜索历史缓存
        readHotSearchCache();           // 读取热搜缓存
    }

    /* 插入搜索关键词 */
    public void addSearchKeyWord(String keyWord){
        if(keyWord == null)
            return;
        for(int i = 0, j = searchHistoryView.getChildCount(); i < j; i++){
            TextView searchItem = (TextView) searchHistoryView.getChildAt(i);
            String itemWord = searchItem.getText().toString();
            if(keyWord.equals(itemWord)){
                searchHistoryView.removeView(searchItem);
                searchHistoryView.addView(searchItem, 0);
                return;
            }
        }
        TextView textView = new TextView(context);
        textView.setTextColor(getResources().getColor(R.color.font_black_think));
        textView.setPadding((int)getResources().getDimension(R.dimen.space_min),
                (int)getResources().getDimension(R.dimen.space_min_more),
                (int)getResources().getDimension(R.dimen.space_min),
                (int)getResources().getDimension(R.dimen.space_min_more));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.min_font));
        textView.setGravity(Gravity.CENTER);
        textView.setBackground(getResources().getDrawable(R.drawable.search_history_item_bg));
        textView.setText(keyWord);
        textView.setOnClickListener(searchHistoryItemClickListener);
        searchHistoryView.addView(textView, 0);
        clearHistory.setVisibility(View.VISIBLE);

        int searchItemCount = searchHistoryView.getChildCount();
        if(searchItemCount == 11)
            searchHistoryView.removeViewAt(10);
        else if(searchItemCount > 11)
            searchHistoryView.removeViews(10, searchItemCount-1);
    }

    /* 缓存搜索历史 */
    public void saveSearchHistoryToCache(){
        List<String> searchHistory = new ArrayList<>();
        for(int i = 0, j = searchHistoryView.getChildCount(); i < j; i++)
            searchHistory.add(((TextView)searchHistoryView.getChildAt(i)).getText().toString());
        saveDataToCache(searchHistory, searchHistoryCachePath);
    }

    /* 读取历史记录缓存 */
    private void readSearchHistroyCache(){
        Observable.create(new Observable.OnSubscribe<List<String>>(){
            @Override
            public void call(Subscriber<? super List<String>> subscriber) {
                List<String> historyDatas = (List<String>) cacheManager.readObject(searchHistoryCachePath);
                subscriber.onNext(historyDatas);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<String>>(){
            @Override
            public void onCompleted() {}
            @Override
            public void onError(Throwable e) {}
            @Override
            public void onNext(List<String> strings) {
                if(strings == null)
                    return;
                for(int i = strings.size()-1; i >= 0; i--)
                    addSearchKeyWord(strings.get(i));
            }
        });
    }

    /* 读取热搜缓存 */
    private void readHotSearchCache(){
        Observable.create(new Observable.OnSubscribe<List<PopularSearchModel>>(){
            @Override
            public void call(Subscriber<? super List<PopularSearchModel>> subscriber) {
                List<PopularSearchModel> hotSearchCache = (List<PopularSearchModel>) cacheManager.readObject(hotSearchCachePath);
                subscriber.onNext(hotSearchCache);
            }
        }).subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<List<PopularSearchModel>>(){
            @Override
            public void onCompleted() {
                getHotSearch(type, 1);
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<PopularSearchModel> popularSearchModels) {
                hotSearchModels.clear();
                if(popularSearchModels != null && popularSearchModels.size() > 0)
                    hotSearchModels.addAll(popularSearchModels);
                hotSearchAdapter.updateAdapter(hotSearchModels);
                onCompleted();
            }
        });
    }

    /* 获取热搜关键词 */
    private void getHotSearch(int type, int page){
        JsonObject param = new JsonObject();
        param.addProperty("type", type);
        param.addProperty("page", page);
        param.addProperty("recommendAction", type==0?1:2);
        param.addProperty("action", 2);
        HttpHelper.getInstance(context).hotSearch(param, 0x01, this);
    }

    @Override
    public void onClick(View v) {
        if(v == clearHistory) {
            searchHistoryView.removeAllViews();
            clearHistory.setVisibility(View.GONE);
        }
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else{
            hotSearchModels.clear();
            List<PopularSearchModel> hotSearchList = data.getList(PopularSearchModel.class);
            if(hotSearchList != null && hotSearchList.size() > 0)
                hotSearchModels.addAll(hotSearchList);
            hotSearchAdapter.updateAdapter(hotSearchModels);
            saveDataToCache(hotSearchModels, hotSearchCachePath);
        }
    }

    /* 保存数据到缓存 */
    private void saveDataToCache(final Object object, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(object, path);
            }
        }).start();
    }

    private OnSearchClickListener searchClickListener;
    public void setHistoryItemClickListener(OnSearchClickListener listener){
        this.searchClickListener = listener;
    }
    public interface OnSearchClickListener{
        void onSearchClick(String keyWord);
    }
}
